package com.dacool.signature;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dacool.util.MD5;

public class Signature {

	private String EMPTY_STRING = "";
	private Map<String, String> params = new HashMap<String, String>();
	private String token = "fba95e7bd17ed3ba3620adda9ed5f03d";

	public void addParam(String key, String value) {
		if (value == null)
			return;
		params.put(key, value);
	}

	public String getParam(String key) {
		if (params.containsKey(key))
			return params.get(key);
		return EMPTY_STRING;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getToken() {
		return this.token;
	}

	public boolean verifySign(Signature signature, String sign) {
		String newSign = signature.doSignature();
		if (newSign.equals(sign))
			return true;
		return false;
	}

	public String doSignature() {
		// step1:sort from params
		List<String> names = new ArrayList<String>();
		for (String keyName : params.keySet())
			names.add(keyName);
		Collections.sort(names);

		// step2:assemble params
		StringBuffer sb = new StringBuffer();
		for (String name : names) {
			String value = params.get(name);
			sb.append(name + value);
		}
		String sign = "";
		try {
			// step3:md5 for params's string
			String md5 = MD5.md5(sb.toString());
			// md5 = md5.toLowerCase();

			sign = MD5.md5(md5.toUpperCase() + token);
		} catch (Exception ex) {
			//
		}
		return sign.toUpperCase();
		// return EMPTY_STRING;
	}
}
